package com.bestcem.xm.wallet.grpc.client;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgWalletConfigRequest;
import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgWalletConfigResponse;
import com.bestcem.bp.xm.user.grpc.v1.services.OrgWalletConfigServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.wallet.grpc.client.converter.WalletConfigGrpcConvert;
import com.bestcem.xm.wallet.grpc.client.dto.OrganizationWalletConfigDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("walletOrganizationWalletConfigGrpcService")
public class OrganizationWalletConfigGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgWalletConfigServiceGrpc.OrgWalletConfigServiceBlockingStub stub;

    @Resource
    private WalletConfigGrpcConvert walletConfigGrpcConvert;

    /**
     * 根据公司id查询公司钱包配置
     *
     * @param orgId 公司id
     * @return OrganizationWalletConfigDTO
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/5/16 10:11
     */
    public OrganizationWalletConfigDTO getOrgWalletConfig(String orgId) {
        // 校验参数
        if (!ObjectId.isValid(orgId)) {
            log.error("根据公司id查询公司钱包配置。请求失败。参数不合法。orgId = [{}]", orgId);
            return null;
        }
        // 设置请求参数
        GetOrgWalletConfigRequest request = GetOrgWalletConfigRequest.newBuilder().setOrgId(orgId).build();
        // 请求
        GetOrgWalletConfigResponse response = null;
        try {
            response = stub.getOrgWalletConfig(request);
        } catch (Exception e) {
            log.error("根据公司id查询公司钱包配置。请求失败", e);
        }
        // 返回值处理
        if (response != null && Code.OK_VALUE == response.getStatus().getCodeValue()) {
            if (log.isInfoEnabled()) {
                log.info("根据公司id查询公司钱包配置。response:{}", response.toString());
            }
            return walletConfigGrpcConvert.orgWalletConfigGrpc2Dto(response.getConfig());
        } else {
            log.error("根据公司id查询公司钱包配置。请求失败, response:{}", response != null ? response.toString() : null);
        }
        return null;
    }
}
